package blog.topics;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2. 设置参数
        factory.setHost(Constants.HOST); // ip 的默认值为 localhost
        factory.setPort(Constants.PORT); // 默认值为 5672
        factory.setVirtualHost(Constants.VIRTUAL_HOST); // 虚拟主机，默认值为 /
        // 账号
        factory.setUsername(Constants.USER_NAME); // 用户名，默认为 guest
        factory.setPassword(Constants.USER_PASSWORD); // 密码，默认为 guest
        // 3. 创建连接 Connection
        Connection connection = factory.newConnection(); // 需要处理异常，在此处直接抛出，并不进行处理
        // 4. 创建 Channel
        Channel channel = connection.createChannel();
        // 5. 声明交换机
        channel.exchangeDeclare(Constants.TOPICS_CHANGE, BuiltinExchangeType.TOPIC, true, false, false, null);
        // 6. 声明队列
        channel.queueDeclare(Constants.TOPICS_QUEUE_1, true, false, false, null);
        channel.queueDeclare(Constants.TOPICS_QUEUE_2, true, false, false, null);
        // 7. 绑定交换机和队列
        channel.queueBind(Constants.TOPICS_QUEUE_1, Constants.TOPICS_CHANGE, "*.a.*", null);
        channel.queueBind(Constants.TOPICS_QUEUE_2, Constants.TOPICS_CHANGE, "*.*.b", null);
        channel.queueBind(Constants.TOPICS_QUEUE_2, Constants.TOPICS_CHANGE, "c.#", null);
        // 8. 发送消息
        String message1 = "test work.a.b";
        channel.basicPublish(Constants.TOPICS_CHANGE, "work.a.b", null, message1.getBytes());
        String message2 = "test a.a.a";
        channel.basicPublish(Constants.TOPICS_CHANGE, "a.a.a", null, message2.getBytes());
        String message3 = "test c.work.a";
        channel.basicPublish(Constants.TOPICS_CHANGE, "c.work.a", null, message3.getBytes());
        System.out.println("消息发送成功!");
        // 9. 释放资源
        channel.close();
        connection.close();
    }
}
